const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');
// const ExposeLoader = require('expose-loader');
const webpack = require('webpack');
// module.exports = (env, argv) => {
// }
module.exports = {
  mode: process.env.NODE_ENV, // 设置模式，默认为production
  // devtool: 'hidden-source-map',
  devtool: false,
  devServer: {
    port: 9100,
    open: true,
    contentBase: path.resolve(__dirname, 'dist'), // 额外的静态文件目录
    compress: true, // 是否启动压缩 gzip
  },
  entry: './src/index.js', // 方式1.设置入口文件
  output: { // 设置出口文件，告诉webpack打包后的bundle输出到那个位置，如何命名这些文件
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
  },
  module: { // loader webpack 只能识别js和json文件，loader用来处理其他类型的文件
    rules: [
      {
        test: require.resolve('lodash'),
        loader: 'expose-loader',
        options: {
          exposes: {
            globalName: '_',
            override: true,
          },
        },
      },
      {
        test: /\.js$/,
        loader: 'eslint-loader', // 进行代码风格检查
        enforce: 'pre', // 给loader进行分类，pre=>normal=>inline=>post
        options: { fix: true }, // 如果发现不合要求，会自动修复
        exclude: ['/node_modules/', '/dist/'], // 排除node_modules文件
      },
      {
        test: /\.js$/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env', '@babel/preset-react'],
              plugins: [
                ['@babel/plugin-proposal-decorators', { legacy: true }],
                ['@babel/plugin-proposal-class-properties', { loose: true }],
              ],
            },
          },
        ],
      },
      {
        test: /\.txt$/, // 要处理的文件后缀
        use: 'raw-loader', // 处理所使用的loader
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader'],
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        test: /\.(png|jgp|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 6 * 1024,
              esModule: false,
              // name:'[path][name].[ext]'
              name: '[hash:10].[ext]',
            },
          },
        ],
      },
    ],
  },
  plugins: [// plugin的作用：打包优化，资源管理，注入环境变量
    new HtmlWebpackPlugin({ template: './src/index.html' }), // 将模板html打包到dist目录，并引入打包后的bundle
    new webpack.SourceMapDevToolPlugin({ // source-map插件工具
      append: '\n//# sourceMappingURL=http://127.0.0.1:8081/[url]',
      filename: '[file].map',
    }),
    new FileManagerPlugin({
      events: {
        onEnd: {
          copy: [{
            source: './dist/*.map',
            destination: path.resolve('maps'),
          }],
          delete: ['./dist/*.map'],
        },
      },
    }),
  ],

};
